package com.lxy.controller.BusinessMan;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lxy.common.R;
import com.lxy.constant.CodeConstant;
import com.lxy.constant.JwtClaimsConstant;
import com.lxy.dto.LoginDTO;
import com.lxy.dto.RegistrationDTO;
import com.lxy.entity.BusinessMan;
import com.lxy.properties.JwtProperties;
import com.lxy.service.BusinessManService;
import com.lxy.utils.JwtUtil;
import com.lxy.utils.ValidateCodeUtils;
import com.lxy.vo.BusinessManLoginVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/business")
public class BusinessManController {
    @Autowired
    private BusinessManService businessManService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JavaMailSenderImpl mailSender;

    /**
     * 商家登录功能
     * @return
     */
    @ApiOperation("商家登录")
    @PostMapping("/login")
    public R<BusinessManLoginVO> login(@RequestBody LoginDTO loginDTO){
        //判断账号是否存在
        String account = loginDTO.getAccount();
        LambdaQueryWrapper<BusinessMan> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BusinessMan::getAccount,account);
        BusinessMan businessMan = businessManService.getOne(lambdaQueryWrapper);
        if(businessMan==null){
            //账号不存在
            return R.error("账号不存在，请先注册");
        }
        //账号存在,判断密码是否正确
        String password = DigestUtils.md5DigestAsHex(loginDTO.getPassword().getBytes());
        if(!password.equals(businessMan.getPassword())){
            //密码不正确
            return R.error("账号或密码错误,请重试");
        }
        //判断账号是否被审核
        if(businessMan.getStatus()==0){
            return R.error("账号正在审核中");
        }
        if(businessMan.getBanded()==0){
            return R.error("账号被禁用，请联系管理员");
        }
        //登录成功，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.BUSINESSMAN_ID, businessMan.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getBusinessManSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        BusinessManLoginVO businessManLoginVO=new BusinessManLoginVO();
        businessManLoginVO.setToken(token);
        businessManLoginVO.setBusinessMan(businessMan);
        return R.success(businessManLoginVO);
    }

    /**
     * 商家注册
     * @param registrationDTO
     * @return
     */
    @ApiOperation("商家注册")
    @PostMapping("/registration")
    public R<String> registration(@RequestBody RegistrationDTO registrationDTO){
        //判断账号名是否重复
        String account = registrationDTO.getAccount();
        LambdaQueryWrapper<BusinessMan> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BusinessMan::getAccount,account);
        BusinessMan getByAccount = businessManService.getOne(lambdaQueryWrapper);
        if(getByAccount!=null){
            return R.error("账号名重复");
        }
        //判断电话号码是否重复
        String phone = registrationDTO.getPhone();
        lambdaQueryWrapper.clear();
        lambdaQueryWrapper.eq(BusinessMan::getPhone,phone);
        BusinessMan getByPhone = businessManService.getOne(lambdaQueryWrapper);
        if(getByPhone!=null){
            return R.error("该手机号已注册");
        }
        //判断邮箱是否重复
        String email = registrationDTO.getEmail();
        lambdaQueryWrapper.clear();
        lambdaQueryWrapper.eq(BusinessMan::getEmail,email);
        BusinessMan getByEmail = businessManService.getOne(lambdaQueryWrapper);
        if(getByEmail!=null){
            return R.error("该邮箱已注册");
        }
        //判断验证码是否正确
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Integer Rcode = (Integer)valueOperations.get(email + CodeConstant.BUSINESSMAN_REGISTRATION);
        if(!Objects.equals(Rcode, registrationDTO.getCode())){
            return R.error("验证码错误");
        }
        //验证码正确，删除redis缓存
        redisTemplate.delete(email + CodeConstant.BUSINESSMAN_REGISTRATION);
        //创建businessMan对象
        BusinessMan businessMan=new BusinessMan();
        BeanUtils.copyProperties(registrationDTO,businessMan);
        String password = DigestUtils.md5DigestAsHex(registrationDTO.getPassword().getBytes());
        businessMan.setPassword(password);
        businessMan.setCreateTime(LocalDateTime.now());
        businessMan.setStatus(0);
        businessMan.setBanded(1);
        businessManService.save(businessMan);
        return R.success("提交成功,将在七个工作日内审核");
    }









}
